package com.fnn.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fnn.entity.User;
import com.fnn.service.UserService;
import com.fnn.util.CaptchaUtil;
import com.fnn.util.EmailUtil;
import com.fnn.util.Hash256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = ("/user"),produces = "application/json;charset=UTF-8")
public class userController {
    CaptchaUtil captchaUtil = new CaptchaUtil();

    @Autowired
    private UserService userService;

    private Hash256Util hash256Util;





    /**
     * 获取登录邮箱验证码
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/get_email_captcha_login")
    public String get_email_captcha_login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s=get_json_parameter(req,resp);
        //将json字符串转换成map
        Map<String,String> mm= JSON.parseObject(s,Map.class);

        String email = mm.get("user_email");

        User u = userService.selectByEmail(email);

        Map<String, String> resp_data = new HashMap<String, String>();
        String json_resp;
        if(u!=null){
            resp_data.put("status", "1");
            resp_data.put("msg", "获取登录验证码成功");
            json_resp = JSONObject.toJSONString(resp_data);

            String email_captcha=captchaUtil.getCaptcha(4);
            //把邮箱验证码保存到session里
            HttpSession session = req.getSession();
            session.setAttribute("email_captcha_login",email_captcha);
            //向用户的邮箱发送验证码
            EmailUtil.sendMail(email,"登录验证",email_captcha);
            return json_resp;
        }else {
            resp_data.put("status", "0");
            resp_data.put("msg", "账户不存在");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }
    }







    /**
     * 获取注册邮箱验证码
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @PostMapping("/get_email_captcha_register")
    @ResponseBody
    public String get_email_captcha_register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s=get_json_parameter(req,resp);
        //将json字符串转换成map
        Map<String,String> mm= JSON.parseObject(s,Map.class);

        String email = mm.get("user_email");

        User u = userService.selectByEmail(email);   //查询该邮箱数据库中是否存在

        Map<String, String> resp_data = new HashMap<String, String>();
        String json_resp;
        if(u!=null){
            resp_data.put("status","0");
            resp_data.put("msg","此邮箱已注册过");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        } else {
            String email_captcha=captchaUtil.getCaptcha(4);
            //把邮箱验证码保存到session里
            HttpSession session = req.getSession();
            session.setAttribute("email_captcha_register",email_captcha);
            //向用户的邮箱发送验证码
            EmailUtil.sendMail(email,"注册账号",email_captcha);

            resp_data.put("status","1");
            resp_data.put("msg","获取注册验证码成功");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }
    }






    /**
     * 注册接口
     * @param req
     * @param resp
     * @param user
     * @return
     * @throws IOException
     */
    @PostMapping("/register")
    @ResponseBody
    public String register(HttpServletRequest req, HttpServletResponse resp, User user) throws IOException {
        String s=get_json_parameter(req,resp);
        System.out.println("json传参="+s);
        //将json字符串转换成map
        Map<String,String> mm= JSON.parseObject(s,Map.class);
        String email = mm.get("user_email");
        String pwd = mm.get("user_password");
        String name = mm.get("user_name");
        String captcha_email=mm.get("captcha_email");

        user.setUser_email(email);
        user.setUser_password(hash256Util.hash256(pwd));
        user.setUser_name(name);
        System.out.println(user);
        HttpSession session=req.getSession();
        String check_code=(String) session.getAttribute("email_captcha_register");   //获取session中的邮箱验证码
        User u = userService.selectByEmail(email);   //查询该邮箱数据库中是否存在
        Map<String, String> resp_data = new HashMap<String, String>();
        String json_resp;
        if(u!=null){
            resp_data.put("status","0");
            resp_data.put("msg","此邮箱已注册过");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        } else if(captcha_email.equals(check_code)){
            userService.register(user);
            resp_data.put("status","1");
            resp_data.put("msg","注册成功");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }else {
            resp_data.put("status","0");
            resp_data.put("msg","注册失败");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }
    }






    /**
     * 密码登录接口
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @PostMapping("/pwdLogin")
    @ResponseBody
    public String login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s=get_json_parameter(req,resp);
        System.out.println("json传参="+s);
        //将json字符串转换成map
        Map<String,String> mm= JSON.parseObject(s,Map.class);


        String user_email = mm.get("user_email");
        String user_password = mm.get("user_password");
        String captcha_picture = mm.get("captcha_picture");
        HttpSession session=req.getSession();
        String check_code=(String) session.getAttribute("captcha_picture");

        User user = userService.selectByEmail(user_email);
        Map<String, String> resp_data = new HashMap<String, String>();
        String json_resp;
        if (captcha_picture.equals(check_code)){
            if (user.getUser_password().equals(hash256Util.hash256(user_password))){

                resp_data.put("status","1");
                resp_data.put("msg","登录成功");
                json_resp = JSONObject.toJSONString(resp_data);

                //创建cookie
                String session_id=session.getId();
                Cookie cookie = new Cookie("session_id", session_id);
                cookie.setMaxAge(24 * 60 * 60);
                cookie.setPath("/"); // 设置Cookie的路径
                //将创建的cookie发送到客户端
                resp.addCookie(cookie);
                userService.insertSessionId(user_email,session_id);   //将session_id保存到数据表里

                return json_resp;
            }else {
                resp_data.put("status","0");
                resp_data.put("msg","账号或密码错误");
                json_resp = JSONObject.toJSONString(resp_data);
                return json_resp;
            }
        }else {
            resp_data.put("status","0");
            resp_data.put("msg","验证码错误");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }
    }









    /**
     * 免密登录接口
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @PostMapping(value = ("/captchaLogin"))
    @ResponseBody
    public String captchaLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s=get_json_parameter(req,resp);
        System.out.println("json传参="+s);
        //将json字符串转换成map
        Map<String,String> mm= JSON.parseObject(s,Map.class);

        String user_email = mm.get("user_email");
        String captcha_email = mm.get("captcha_email");
        HttpSession session=req.getSession();
        String check_code=(String) session.getAttribute("email_captcha_login");

        User user = userService.selectByEmail(user_email);
        Map<String, String> resp_data = new HashMap<String, String>();
        String json_resp;
        if (captcha_email.equals(check_code)){
            resp_data.put("status","1");
            resp_data.put("msg","登录成功");
            json_resp = JSONObject.toJSONString(resp_data);

            //创建cookie
            String session_id=session.getId();
            Cookie cookie = new Cookie("session_id", session_id);
            cookie.setMaxAge(24 * 60 * 60);
            cookie.setPath("/"); // 设置Cookie的路径
            //将创建的cookie发送到客户端
            resp.addCookie(cookie);
            userService.insertSessionId(user_email,session_id);   //将session_id保存到数据表里

            return json_resp;
        }else {
            resp_data.put("status","0");
            resp_data.put("msg","验证码错误");
            json_resp = JSONObject.toJSONString(resp_data);
            return json_resp;
        }
    }









    //获取接送json格式的数据
    public String get_json_parameter(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求参数（json格式数据），获取请求体原始数据流
        BufferedReader reader = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String jsonData = sb.toString();
        // 直接查看原始JSON数据
        System.out.println("原始JSON数据：" + jsonData);
        return jsonData;
    }
}
